<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/4/3
 * Time: 23:53
 */

namespace app\api\model;


class Product extends BaseModel
{
    protected $hidden = [
        'delete_time', 'main_img_id', 'pivot', 'from', 'category_id',
        'create_time', 'update_time'
    ];

    public function getMainImgUrlAttr($value, $data)
    {
        return $this->prefixImgUrl($value, $data);
    }

    public function imgs()
    {
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }

    public function properties()
    {
        return $this->hasMany('ProductProperty', 'product_id', 'id');
    }

    public static function getMostRecent($count)
    {
        // 排序链式方法 order
        // create_time 排序依据字段
        // 对product模型排序
        $products = self::limit($count)
            ->order('create_time desc')
            ->select();
        return $products;
    }

    public static function getProductsByCategoryID($categoryID)
    {
        $products = self::where('category_id', '=', $categoryID)
            ->select();
        return $products;
    }

    public static function getProductDetail($id)
    {
        // 对当前模型下的属性排序
        //$product = self::with('imgs.imgUrl,properties')
        //    ->find($id);
        //$product = self::with(['imgs.imgUrl','properties'])
        //    ->find($id);
        //$product = self::with(['imgs.imgUrl'])
        //    ->with(['properties'])
        //    ->find($id);
        $product = self::with([
            'imgs' => function ($query) {
                $query->with(['imgUrl'])
                    ->order('order', 'asc');
            }
        ])
            ->with(['properties'])
            ->find($id);

        return $product;
    }
}